package org.springblade.modules.auth.endpoint;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.common.config.FeiShuConfiguration;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.enums.FeishuClientEnum;
import org.springblade.core.launch.constant.AppConstant;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.common.utils.feishu.FeiShuUtil;
import org.springblade.modules.auth.utils.FeishuUserInfo;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IUserService;
import org.springframework.web.bind.annotation.*;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

import static org.springblade.modules.admin.service.approve.strategy.ApproveBusinessFlow.bladeRedis;

/**
 * @Description 微信小程序用户令牌
 * @Author ysq
 * @Date 2021/12/16
 **/
@NonDS
@ApiSort(2)
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_AUTH_NAME)
@Api(value = "飞书授权认证", tags = "授权接口")
public class FeiShuTokenEndpoint {

	private final FeiShuConfiguration feiShuConfiguration;
	private final FeiShuUtil feiShuUtil;
	private final IUserService userService;

	@ApiLog("获取飞书appId")
	@GetMapping("/feishu/getAppId")
	@ApiOperation(value = "获取飞书appId")
	public R<String> getAppId() {
		return R.data(feiShuConfiguration.getClitSecure(FeishuClientEnum.CERT).getAppId());
	}

	@ApiLog("飞书免登录请求")
	@PostMapping("/feishu/login/request/{code}")
	@ApiOperation(value = "飞书免登录请求")
	public R<Map<String, String>> loginRequest(@PathVariable String code) {
		String phone;
		try {
			FeishuUserInfo userInfo = feiShuUtil.getUserAccessToken(code);
			phone = userInfo.getSimpleMobile();
		} catch (Exception e) {
			throw new ServiceException("飞书授权错误：" + e);
		}

		User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getPhone, phone).eq(User::getTenantId, "592800"));
		if (Func.isEmpty(user)) {
			throw new ServiceException("您还未加入梯无忧平台，请联系管理员加入！");
		}
		// 设置个临时密码，30秒有效期
		String tempPsw = IdUtil.randomUUID();
		bladeRedis.setEx(CommonConstant.FEISHU_LOGIN_KEY + phone, tempPsw, Duration.ofSeconds(30));
		Map<String, String> map = new HashMap<>(2);
		map.put("phone", phone);
		map.put("tempPsw", tempPsw);
		return R.data(map);
	}
}
